import React, { useState, useRef } from 'react';
import { Modal, message, Button, Result } from 'antd';
import type { ProFormInstance } from '@ant-design/pro-form';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import { EditableProTable } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import ProForm, {
  StepsForm,
  ProFormText,
  ProFormDigit,
  ProFormSelect,
} from '@ant-design/pro-form';
import { PlusOutlined } from '@ant-design/icons';
import { columnsData, IPFSColumns } from './data';
import type { columnsDataType, IPFSListItem } from './data.d';
// 接口
import { getPageList, getThemeIPFSList, mintTheme } from './service';
import { getContractProtocols } from '@/services/services';
import { getDictType } from '@/services/services';
import TableTitle from '@/components/TableTitle';
import { getLocalStorageInfo } from '@/utils/localStorageInfo';

export default ({
  setIsFragments,
  setIsLoadCastingDetail,
  setViewSerialNo,
}) => {
  // 控制铸造模态框
  const [addThemeModal, setAddThemeModal] = useState(false);
  // 新增主题信息
  const [newThemeInfo, setNewThemeInfo] = useState({});
  // 倒计时
  const [countDown, setCountDown] = useState(3);
  // 新增主题类型列表
  const [themeType, setThemeType] = useState();
  // 主题类型
  const [type, setType] = useState('');
  // 合约规则列表
  const [contractProtocol, setContractProtocol] = useState([]);
  // 元数据
  const [themeIPFS, setThemeIPFS] = useState([]);
  // 铸造btn
  const [btnDisabled, setBtnDisabled] = useState(false);
  // 表头数据
  const columns: ProColumns<columnsDataType>[] = columnsData;

  // 操作行数据 自定义操作行
  const actionRender: any = (text: any, record: any, index: number) => (
    <a
      onClick={() => {
        setIsLoadCastingDetail(true);
        setViewSerialNo(record.serialNo);
        setIsFragments(record.fragmentsFlag);
      }}
    >
      详情
    </a>
  );

  // 自定义proTable表格列展示
  columns.forEach((item: any) => {
    item.dataIndex === 'action' ? (item.render = actionRender) : undefined;
  });

  /**
   * 铸造主题按钮调用
   */
  const addNewTheme = async () => {
    let res = await getDictType({
      dictType: 'theme-nft-type',
      pageSize: 10,
      current: 1,
    });
    console.log(res);
    if (res.code !== '000000') {
      message.info('获取主题类型失败，请稍后再试。');
      return;
    }
    setThemeType(
      res.data.map((item: any) => {
        return {
          value: item.itemValue,
          label: item.label,
        };
      }),
    );
    let data = await getContractProtocols({});
    console.log(res);
    setContractProtocol(
      data.data.map((item) => {
        const { protocolCode: label, serialNo: value } = item;
        return {
          label,
          value,
        };
      }),
    );
    setAddThemeModal(true);
  };

  // Table action 的引用，便于自定义触发
  const actionRef = React.useRef<ActionType>();
  const formRef = useRef<ProFormInstance>();

  return (
    <div>
      {/* Pro表格 */}
      <ProTable<columnsDataType>
        headerTitle={<TableTitle title="主题铸造" />}
        scroll={{ x: 900 }}
        bordered
        // 表头
        columns={columns}
        actionRef={actionRef}
        // 请求获取的数据
        request={async (params) => {
          console.log(params);

          let res = await getPageList({ ...params });
          console.log(res);
          const result = {
            data: res.data,
            total: res.pagination.totalSize,
          };
          return result;
        }}
        rowKey="serialNo"
        // 搜索表单的配置--关闭
        search={false}
        form={{
          ignoreRules: false,
        }}
        pagination={{
          pageSize: 10,
        }}
        toolBarRender={() => [
          <Button
            onClick={addNewTheme}
            key="button"
            icon={<PlusOutlined />}
            type="primary"
          >
            铸造主题
          </Button>,
        ]}
      />
      {/* 铸造主题 */}
      <StepsForm
        formRef={formRef}
        //  完成回调 value为填写的表单的信息
        onFinish={async (values) => {
          console.log(values);
          // 关闭模态框
          // setIsCastingModal(false);
          // true最后一步重置表单，回到第一步
          return true;
        }}
        // 表单验证规则
        formProps={{
          validateMessages: {
            required: '此项为必填项',
          },
        }}
        // 自定义整个表单区域，返回的 dom 在表单的外部
        stepsFormRender={(dom, submitter) => {
          return (
            <Modal
              title="主题添加"
              width={900}
              onCancel={() => {
                formRef.current?.resetFields();
                setThemeIPFS([]);
                setBtnDisabled(false);
                setAddThemeModal(false);
              }}
              visible={addThemeModal}
              footer={submitter}
              centered
            >
              {dom}
            </Modal>
          );
        }}
        // 自定义按钮
        submitter={{
          render: (props) => {
            if (props.step === 0) {
              return (
                <Button type="primary" onClick={() => props.onSubmit?.()}>
                  下一步 {'>'}
                </Button>
              );
            }

            if (props.step === 1) {
              return [
                <Button
                  key="pre"
                  onClick={() => {
                    setBtnDisabled(false);
                    props.onPre?.();
                  }}
                >
                  上一步
                </Button>,
                <Button
                  disabled={btnDisabled}
                  type="primary"
                  key="goToTree"
                  onClick={() => props.onSubmit?.()}
                >
                  铸造
                </Button>,
              ];
            }

            return null;
          },
        }}
      >
        {/* 一 基础配置*/}
        <StepsForm.StepForm
          name="base"
          title="基础配置"
          onFinish={async (value) => {
            console.log(value);
            let res = await getThemeIPFSList({
              current: 1,
              pageSize: 30,
              metadataName: value.themeName,
              fragmentsFlag: 0,
            });
            if (!value.fragmentsFlag) {
              if (
                (value.sex == 1 && res.data.length !== 2) ||
                (value.sex == 2 && res.data.length !== 1)
              ) {
                message.info('主题元数据信息不匹配，请检查主题元数据配置');
                setBtnDisabled(true);
              }
              setNewThemeInfo({
                themeMetaDataNos: res.data.map((item) => {
                  return { serialNo: item.serialNo };
                }),
                ...newThemeInfo,
                ...value,
              });
              setThemeIPFS(res.data);
              return true;
            }
            let data = await getThemeIPFSList({
              current: 1,
              pageSize: 30,
              metadataName: value.themeNam,
              fragmentsFlag: 1,
            });
            console.log(res);

            if (
              (value.sex == 1 && data.data.length !== 18) ||
              (value.sex == 2 && data.data.length !== 9)
            ) {
              message.info('碎片元数据信息不匹配，请碎片主题元数据配置');
              setBtnDisabled(true);
            }
            setThemeIPFS([...res.data, ...data.data]);
            setNewThemeInfo({
              themeMetaDataNos: res.data.map((item) => {
                return { serialNo: item.serialNo };
              }),
              fragmentsMetaDataNos: data.data.map((item) => {
                return { serialNo: item.serialNo };
              }),
              ...newThemeInfo,
              ...value,
            });
            return true;
          }}
        >
          <ProFormText
            name="themeName"
            label="主题名称(需与主题元数据对应)"
            placeholder="请输入主题名称"
            rules={[{ required: true }]}
          />
          <ProFormSelect
            name="type"
            label="主题类型"
            placeholder="请输入主题编号"
            rules={[{ required: true }]}
            options={themeType}
            fieldProps={{
              onChange: (e) => {
                setType(e);
                console.log(e);
              },
            }}
          />
          {type == '4' ? (
            <ProFormText
              name="password"
              label="兑换口令"
              placeholder="请输入兑换口令"
              rules={[{ required: true }]}
            />
          ) : null}
          <ProFormSelect
            name="sex"
            label="有无性别"
            placeholder="请选择身份类型"
            rules={[{ required: true }]}
            options={[
              {
                label: '有',
                value: 1,
              },
              {
                label: '无',
                value: 2,
              },
            ]}
          />
          <ProFormSelect
            name="fragmentsFlag"
            label="有无碎片"
            placeholder="请选择身份类型"
            rules={[{ required: true }]}
            options={[
              {
                label: '无碎片',
                value: 0,
              },
              {
                label: '有碎片',
                value: 1,
              },
            ]}
          />
          <ProFormDigit
            name="totalSupply"
            label="总供应量"
            placeholder="请输入总供应量"
            rules={[{ required: true }]}
          />
          {/* 合约协议 */}
          <ProFormSelect
            rules={[{ required: true }]}
            options={contractProtocol}
            name="contractTemplateNo"
            label="合约协议"
          />
        </StepsForm.StepForm>
        {/* 二 元数据配置*/}
        <StepsForm.StepForm
          name="checkbox"
          title="元数据配置"
          onFinish={async (values) => {
            let customerNo = getLocalStorageInfo('customerInfo').customerNo;
            let res = await mintTheme({
              ...newThemeInfo,
              customerNo,
            });
            console.log(res);
            if (res.code === '000000') {
              // console.log(dataSource);
              message.success('添加成功');
              let a = countDown;
              let countDowns = setInterval(() => {
                setCountDown(a - 1);
                a = a - 1;
                if (a === 0) {
                  console.log(a);
                  setAddThemeModal(false);
                  formRef.current?.submit();
                  setCountDown(3);
                  clearInterval(countDowns);
                  // 表格重新渲染
                  actionRef.current?.reload();
                }
              }, 1000);
              return true;
            }
          }}
        >
          {/* 元数据列表 */}
          <ProTable<IPFSListItem>
            columns={IPFSColumns}
            scroll={{ x: 800 }}
            dataSource={themeIPFS}
            rowKey="serialNo"
            pagination={{
              showQuickJumper: true,
            }}
            search={false}
            dateFormatter="string"
            headerTitle="元数据"
            toolBarRender={false}
          />
        </StepsForm.StepForm>
        {/* 三 添加完成*/}
        <StepsForm.StepForm name="time" title="添加完成">
          <Result status="success" title="添加成功！" />
          <span
            style={{
              display: 'inline-block',
              width: '100%',
              textAlign: 'center',
            }}
          >
            {countDown}秒后退出
          </span>
        </StepsForm.StepForm>
      </StepsForm>
    </div>
  );
};
